<template>
  <!-- 申请发票的页面 -->
  <div class="receiptDialogContainer">
    <el-drawer
      :title="
        operateType === 'add'
          ? '申请开票'
          : operateType === 'edit'
          ? '编辑发票'
          : '发票详情'
      "
      :before-close="handleClose"
      :visible.sync="dialogVisible"
      direction="rtl"
      custom-class="demo-drawer"
      :wrapperClosable="false"
      @open="beforeOpenDrawer"
      ref="drawer"
      size="40%"
    >
      <div class="demo-drawer__content">
        <el-form
          label-position="right"
          :model="formData"
          :rules="rules"
          ref="formName"
        >
          <!-- <el-form-item
            class="formItemWidth"
            label="对账单号："
            :label-width="formLabelWidth"
            prop="account_no_receive"
          >
            <span>{{ account_no || account_no_receive }}</span>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="客户名称："
            :label-width="formLabelWidth"
            prop="customer_name"
          >
            <span>{{ account_customer_name || customer_name_receive }}</span>
          </el-form-item> -->
          <div style="font-size: 14px; color: #707175">
            <span style="margin: 0 37px"
              >对账单号：{{ account_no || account_no_receive }}</span
            >
            <span
              >客户名称：{{
                account_customer_name || customer_name_receive
              }}</span
            >
          </div>
          <div class="formTitle">抬头信息</div>
          <el-form-item
            class="formItemWidth"
            label="发票主体名称："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.invoice_body_name"
            required
          >
            <el-select
              :disabled="operateType === 'info'"
              allow-create
              filterable
              clearable
              @clear="
                formData.customer_invoice_book_info.invoice_body_name = '';
                formData.customer_invoice_book_info.invoice_body_id = 0;
                company_invoice_book_list = invoiceBookList;
              "
              reserve-keyword
              style="width: 100%"
              placeholder="请输入发票主体名称"
              @change="selectInvoiceCustomer"
              v-model="formData.customer_invoice_book_info.invoice_body_name"
            >
              <el-option
                v-for="item in customer_invoice_book_list"
                :key="item.id"
                :label="item.invoice_body_name"
                :value="item.invoice_body_name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="纳税人识别号："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.taxpayer_identify_number"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入纳税人识别号"
              v-model="
                formData.customer_invoice_book_info.taxpayer_identify_number
              "
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="公司地址："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.company_address"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入公司地址"
              v-model="formData.customer_invoice_book_info.company_address"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="公司电话："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.company_phone"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入公司电话"
              v-model="formData.customer_invoice_book_info.company_phone"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="开户行："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.bank_of_deposit"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入开户行"
              v-model="formData.customer_invoice_book_info.bank_of_deposit"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="开户行账号："
            :label-width="formLabelWidth"
            prop="customer_invoice_book_info.account_no"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请输入开户行账号"
              v-model="formData.customer_invoice_book_info.account_no"
            ></el-input>
          </el-form-item>
          <div class="formTitle">发票信息</div>
          <el-form-item
            class="formItemWidth"
            label="发票类型："
            :label-width="formLabelWidth"
            prop="invoice_type"
          >
            <el-select
              :disabled="operateType === 'info'"
              clearable
              style="width: 100%"
              placeholder="请选择发票类型"
              v-model="formData.invoice_type"
            >
              <el-option label="专用发票" value="0"></el-option>
              <el-option label="普通发票" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="发票金额："
            :label-width="formLabelWidth"
            required
          >
            <el-input disabled v-model="formData.amount"
              ><template slot="append">元</template></el-input
            >
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="发票类目："
            :label-width="formLabelWidth"
            prop="category"
          >
            <el-select
              :disabled="operateType === 'info'"
              @change="selectCategory"
              clearable
              style="width: 250px"
              v-model="formData.category"
              placeholder="请选择发票类目"
            >
              <el-option label="运输服务*运输费" value="0"></el-option>
              <el-option label="运输服务*物流辅助服务" value="1"></el-option>
              <el-option
                label="经纪代理服务*国内货物运输代理服务"
                value="2"
              ></el-option>
            </el-select>
            <span style="margin-left: 20px">税率：{{ formData.rate }}%</span>
          </el-form-item>
          <!-- 我方发票主体是选择了开票名称主体之后带出来的，输入的情况就用api请求 -->
          <el-form-item
            class="formItemWidth"
            label="我方发票主体："
            :label-width="formLabelWidth"
            prop="company_invoice_book_id"
          >
            <el-select
              style="width: 100%"
              v-if="formData.customer_invoice_book_info.invoice_body_id !== 0"
              disabled
              @change="selectCompanyInvoiceBook"
              v-model="formData.company_invoice_book_id"
            >
              <el-option
                v-for="item in company_invoice_book_list"
                :key="item.relation_invoice_body_id"
                :label="item.relation_invoice_body_name"
                :value="item.relation_invoice_body_id"
              ></el-option>
            </el-select>
            <el-select
              v-else
              style="width: 100%"
              :disabled="operateType === 'info'"
              @change="selectCompanyInvoiceBook"
              v-model="formData.company_invoice_book_id"
            >
              <el-option
                v-for="item in company_invoice_book_list"
                :key="item.id"
                :label="item.invoice_body_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :required="formData.rate === '9'"
            class="formItemWidth"
            label="运输货物："
            :label-width="formLabelWidth"
            prop="transport_of_goods"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="例：常温药品，税率9%必填"
              v-model="formData.transport_of_goods"
            ></el-input>
          </el-form-item>
          <el-form-item
            :required="formData.rate === '9'"
            class="formItemWidth"
            label="运输车牌号："
            :label-width="formLabelWidth"
            prop="vehicle_number"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="税率9%必填"
              v-model="formData.vehicle_number"
            ></el-input>
          </el-form-item>
          <el-form-item
            :required="formData.rate === '9'"
            class="formItemWidth"
            label="车辆型号："
            :label-width="formLabelWidth"
            prop="vehicle_type"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="例：4.2米冷藏车，税率9%必填"
              v-model="formData.vehicle_type"
            ></el-input>
          </el-form-item>
          <el-form-item
            :required="formData.rate === '9'"
            class="formItemWidth"
            label="起止地："
            :label-width="formLabelWidth"
            prop="start_stop_place"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="例：北京-广州，税率9%必填"
              v-model="formData.start_stop_place"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="预计回款时间："
            :label-width="formLabelWidth"
            prop="receivable_time"
          >
            <el-date-picker
              :disabled="operateType === 'info'"
              v-model="formData.receivable_time"
              type="datetime"
              align="right"
              value-format="timestamp"
              unlink-panels
              :picker-options="pickerOptions"
              style="width: 100%"
            />
          </el-form-item>
          <div class="formTitle">其它信息</div>
          <el-form-item
            class="formItemWidth"
            label="对账单需要盖章邮寄"
            prop="account_is_sealed_by_mail"
            label-width="160px"
          >
            <el-radio-group
              v-model="formData.account_is_sealed_by_mail"
              :disabled="operateType === 'info'"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="对账单邮寄地址："
            label-width="145px"
            prop="account_mailing_address"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="请填写邮寄地址"
              v-model="formData.account_mailing_address"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="其它备注："
            prop="remark"
            label-width="145px"
          >
            <el-input
              :disabled="operateType === 'info'"
              placeholder="备注说明"
              type="textarea"
              v-model="formData.remark"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="formItemWidth"
            label="附件："
            prop="attachment"
            label-width="145px"
          >
            <el-upload
              :disabled="operateType === 'info'"
              class="upload-demo"
              action
              :auto-upload="false"
              :on-preview="handlePreview"
              :on-remove="handleRemoveAttachment"
              :before-remove="beforeRemoveAttachment"
              :on-change="handleChangeAttachment"
              multiple
              :file-list="fileList"
              list-type="picture"
            >
              <el-button plain size="small" type="primary" icon="el-icon-upload"
                >点击上传</el-button
              >
              <!-- <span slot="tip" class="el-upload__tip" style="margin-left: 20px"
                >支持扩展名：</span
              > -->
            </el-upload>
            <el-dialog :visible.sync="dialogImageVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            v-show="operateType !== 'info'"
            type="primary"
            @click="submitForm('formName')"
            :loading="loading"
            >{{ operateType === "add" ? "发起申请" : "保存" }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { timestamp10 } from "@/utils/mUtils";
import {
  reqReceiptReturn,
  reqEditReceipt,
  reqReceiptBookList,
  reqReceiptInfo,
  reqHistoryReceiptInfo,
} from "@/api/finance";
import { uploading } from "@/page/material/common/common";
export default {
  name: "receiptDialog",
  props: [
    "account_no",
    "account_id",
    "account_customer_id",
    "account_customer_name",
    "now_price",
    "invoice_id",
  ],
  data() {
    let validate_transport_of_goods = (rule, value, callback) => {
      if (this.formData.rate === "9" && value === "") {
        callback(new Error("请输入运输货物"));
      } else {
        callback();
      }
    };
    let validate_vehicle_number = (rule, value, callback) => {
      if (this.formData.rate === "9" && value === "") {
        callback(new Error("请输入运输货车牌号"));
      } else {
        callback();
      }
    };
    let validate_vehicle_type = (rule, value, callback) => {
      if (this.formData.rate === "9" && value === "") {
        callback(new Error("请输入车辆型号"));
      } else {
        callback();
      }
    };
    let validate_start_stop_place = (rule, value, callback) => {
      if (this.formData.rate === "9" && value === "") {
        callback(new Error("请输入起止地"));
      } else {
        callback();
      }
    };
    return {
      operateType: "", //操作类型
      dialogVisible: false,
      loading: false,
      account_no_receive: "",
      customer_name_receive: "",
      invoiceBookList: [], //请求到的列表
      customer_invoice_book_list: [], //发票簿的下拉列表
      company_invoice_book_list: [], //我方发票主体的列表
      formData: {
        account_id: "", // 对账单id
        customer_id: "", // 客户id
        customer_invoice_book_info: {
          invoice_body_id: 0, // 发票主体id
          invoice_body_name: "", // 发票主体名
          taxpayer_identify_number: "", // 纳税人识别号
          company_address: "", // 公司地址
          company_phone: "", // 公司电话
          bank_of_deposit: "", // 开户行
          account_no: "", // 开户行账号
        }, // 发票主体信息(客户)
        company_invoice_book_id: "", // 发票主体id(公司)
        invoice_type: "", // 发票类型：0-专用发票，1-普通发票
        amount: "", //发票金额
        category: "", // 发票类目
        rate: "", // 税率
        transport_of_goods: "", // 运输货物
        vehicle_number: "", // 运输车牌号
        vehicle_type: "", // 车辆型号
        start_stop_place: "", // 起止地
        receivable_time: "", // 预计回款时间
        account_is_sealed_by_mail: "0", // 对账单是否需要盖章邮寄：0-否，1-是
        account_mailing_address: "", // 对账单邮寄地址
        remark: "", // 备注
        attachment: [], // 附件
      },
      fileList: [], //上传的附件
      dialogImageVisible: false, //附件预览
      dialogImageUrl: "", //预览的图片路径
      rules: {
        // name: [
        //   { required: true, message: "请输入活动名称", trigger: "blur" },
        //   { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        // ],
        "customer_invoice_book_info.invoice_body_name": [
          { required: true, message: "请输入发票主体名称", trigger: "change" },
        ],
        "customer_invoice_book_info.taxpayer_identify_number": [
          { required: true, message: "请输入纳税人识别号", trigger: "blur" },
        ],
        "customer_invoice_book_info.company_address": [
          { required: true, message: "请输入公司地址", trigger: "blur" },
        ],
        "customer_invoice_book_info.company_phone": [
          { required: true, message: "请输入公司电话", trigger: "blur" },
        ],
        "customer_invoice_book_info.bank_of_deposit": [
          { required: true, message: "请输入开户行", trigger: "blur" },
        ],
        "customer_invoice_book_info.account_no": [
          { required: true, message: "请输入开户行账号", trigger: "blur" },
        ],
        invoice_type: [
          { required: true, message: "请输入发票类型", trigger: "change" },
        ],
        category: [
          { required: true, message: "请输入发票类目", trigger: "change" },
        ],
        company_invoice_book_id: [
          { required: true, message: "请输入我方发票主体", trigger: "change" },
        ],
        transport_of_goods: [
          { validator: validate_transport_of_goods, trigger: "blur" },
        ],
        vehicle_number: [
          { validator: validate_vehicle_number, trigger: "blur" },
        ],
        vehicle_type: [{ validator: validate_vehicle_type, trigger: "blur" }],
        start_stop_place: [
          { validator: validate_start_stop_place, trigger: "blur" },
        ],
        account_is_sealed_by_mail: [
          { required: true, message: "请选择是否需要邮寄", trigger: "change" },
        ],
        receivable_time: [
          { required: true, message: "请输入预计回款时间", trigger: "change" },
        ],
      },
      formLabelWidth: "145px",
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      timer: null,
    };
  },
  methods: {
    async beforeOpenDrawer() {
      this.$nextTick(async () => {
        this.operateType = this.$store.getters.operateType;
        let result2 = await reqReceiptBookList({
          body_belong: "0", //请求我方发票主体公司
        });
        if (result2.code === 10000) {
          this.invoiceBookList = result2.data;
          this.company_invoice_book_list = result2.data;
        }
        if (this.operateType === "edit" || this.operateType === "info") {
          let result = await reqReceiptInfo({
            id: this.invoice_id,
          });
          if (result.code === 10000) {
            this.formData = result.data;
            this.company_invoice_book_list = [
              result.data.company_invoice_book_info,
              // id:result.data.company_invoice_book_info
            ];
            this.formData.company_invoice_book_id =
              result.data.company_invoice_book_info.invoice_body_id * 1;
            this.formData.receivable_time =
              this.formData.receivable_time * 1000;
            this.fileList = result.data.attachment.map((url) => {
              return url;
            });
            this.account_no_receive = result.data.account_no;
            this.customer_name_receive = result.data.customer_name;
            this.formData.account_id = result.data.account_id * 1;
            this.formData.customer_id = result.data.customer_id * 1;
            this.formData.amount = result.data.amount + "";
          }
        } else {
          let result = await reqHistoryReceiptInfo({
            account_id: this.account_id * 1,
          });
          if (result.code === 10000) {
            if (result.data) {
              this.formData = result.data;
              this.company_invoice_book_list = [
                result.data.company_invoice_book_info,
              ];
              this.formData.company_invoice_book_id =
                result.data.company_invoice_book_info.invoice_body_id * 1;
              this.formData.receivable_time =
                this.formData.receivable_time * 1000;
              this.fileList = result.data.attachment.map((url) => {
                return url;
              });
              this.account_no_receive = result.data.account_no;
              this.customer_name_receive = result.data.customer_name;
              this.formData.account_id = result.data.account_id * 1;
              this.formData.customer_id = result.data.customer_id * 1;
              this.formData.amount = result.data.amount + "";
            } else {
              this.formData.account_id = this.account_id * 1;
              this.formData.customer_id = this.account_customer_id * 1;
              this.formData.amount = this.now_price + "";
              this.account_no_receive = this.account_no;
              this.customer_name_receive = this.account_customer_name;
            }
          }
        }

        let result1 = await reqReceiptBookList({
          body_belong: "1", //请求发票主体客户下拉用这个
          belong_to_id: this.formData.customer_id * 1, //对账单上的客户id
          invoice_body_name: "", //发票主体名
        });
        if (result1.code === 10000) {
          this.customer_invoice_book_list = result1.data;
        }
      });
    },
    async selectInvoiceCustomer(val) {
      const { customer_invoice_book_info } = this.formData;
      let piece = this.customer_invoice_book_list.find(
        (item) => item.invoice_body_name === val
      );
      if (piece) {
        customer_invoice_book_info.invoice_body_id = piece.id;
        // this.company_invoice_book_list = this.customer_invoice_book_list; //如果选择了客户发票主体,那就直接带出piece里面的公司主体
        this.formData.customer_invoice_book_info.invoice_body_id = piece.id;
        customer_invoice_book_info.invoice_body_name = piece.invoice_body_name;
        customer_invoice_book_info.taxpayer_identify_number =
          piece.taxpayer_identify_number;
        customer_invoice_book_info.company_address = piece.company_address;
        customer_invoice_book_info.company_phone = piece.company_phone;
        customer_invoice_book_info.bank_of_deposit = piece.bank_of_deposit;
        customer_invoice_book_info.account_no = piece.account_no;
        this.company_invoice_book_list = [
          {
            relation_invoice_body_id: piece.relation_invoice_body_id,
            relation_invoice_body_name: piece.relation_invoice_body_name,
          },
        ];
        this.formData.company_invoice_book_id = piece.relation_invoice_body_id;
      } else {
        customer_invoice_book_info.invoice_body_id = 0;
      }
    },
    selectCompanyInvoiceBook() {
      this.$forceUpdate();
      // if (
      //   this.formData.customer_invoice_book_info.invoice_body_id * 1 !==
      //   NaN
      // ) {
      //   this.formData.customer_invoice_book_info.invoice_body_name =
      //     this.formData.customer_invoice_book_info.invoice_body_id;
      //   this.formData.customer_invoice_book_info.invoice_body_id = "";
      // }
    },
    selectCategory(val) {
      //看看动态表单验证升不生效
      if (val === "0") {
        this.formData.rate = "9";
      } else {
        this.formData.rate = "6";
      }
    },
    //上传附件的函数
    beforeRemoveAttachment(file, fileList) {
      return this.$confirm("是否删除该附件");
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    handleRemoveAttachment(file, fileList) {
      const index = this.fileList.findIndex(
        (item, index) => item.uid === file.uid
      ); //找到被删除的id
      // console.log(index);
      if (index > -1) {
        this.formData.attachment.splice(index, 1);
        this.fileList.splice(index, 1);
      }
    },
    handleChangeAttachment(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        // this.formData.attachment.push(res.res.requestUrls[0]);
        this.formData.attachment.push({
          uid: file.uid,
          url: res.res.requestUrls[0],
        });
      });
    },

    handleClose() {
      // this.$refs.formName.resetFields();
      this.dialogVisible = false;
    },
    submitForm(formName) {
      //提交验证表单
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //在这里写提交
          this.formData.receivable_time = timestamp10(
            this.formData.receivable_time
          );
          let result;
          if (this.operateType === "add") {
            result = await reqReceiptReturn(this.formData);
          } else {
            result = await reqEditReceipt(this.formData);
          }
          if (result.code === 10000) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.$parent.displayOrders();
            // this.$refs[formName].resetFields();
            // Object.assign(this.$data, this.$options.data());
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    cancelForm() {
      this.loading = false;
      // this.$refs.formName.resetFields();
      this.dialogVisible = false;
      clearTimeout(this.timer);
    },
  },
};
</script>

<style scoped lang="less">
.receiptDialogContainer {
  .demo-drawer__content {
    margin-top: -20px;
    .formItemWidth {
      width: 500px;
    }
    .formTitle {
      margin: 20px 25px;
      font-weight: bold;
    }
    .demo-drawer__footer {
      width: 100%;
      display: flex;
      justify-content: center;
      padding-bottom: 10px;
    }
  }
}
</style>